import React, {type MutableRefObject} from 'react';
import Request from "@/service/request";
import HoverTooltip from "@/components/HoverTooltip";
import {Button, Card, DatePicker, Form, Input, Popconfirm, Select, Space, Table, TableColumnsType, Tag} from "antd";
import {DeleteOutlined, PlusOutlined, SearchOutlined, SyncOutlined} from "@ant-design/icons";
import {useImmer} from "use-immer";
import {filterParams, formatDateParams} from "@/utils";
import {usePagination} from "@/hooks/modules/usePagination";
import {message, modal} from '@/hooks/modules/useMessage';
import DialogRole from "@/views/system/role/components/DialogRole";
import {useActivate, useUnactivate} from "react-activation";

// 定义状态类型
type RoleStatus = { value: number, name: '启用' | '禁用' };

// 定义角色数据类型
type rowData = {
    id: number,
    roleName: string,
    roleKey: string,
    status: number,
    createTime: string,
    remark: string,
};

// 分离状态列表为常量
const statusList: RoleStatus[] = [
    {value: 1, name: '启用'},
    {value: 0, name: '禁用'},
];
const Role = () => {

        const [form] = Form.useForm();
        //列表数据
        const [dataList, setDataList] = React.useState<rowData[]>([])
        //分页总数
        const [total, setTotal] = React.useState<number>(0)
        //查询条件数据
        const [searchForm, setSearchForm] = useImmer({pageNo: 1, pageSize: 10});
        //选中的数据keys
        const [selectedRowKeys, setSelectedRowKeys] = React.useState<React.Key[]>([])
        //选中的数据row
        const [selectedRow, setSelectedRow] = React.useState<rowData[]>([])
        //获取弹窗组件实例
        const dialogRoleRef: MutableRefObject<any> = React.useRef(null);

        const columns: TableColumnsType<rowData> = [
            {
                title: '角色名称',
                dataIndex: 'roleName',
                align: 'center',
                width: 300,
                ellipsis: {showTitle: false},
                render: (text: string | number) => <HoverTooltip title={text}>{text}</HoverTooltip>
            },
            {
                title: '权限字符',
                dataIndex: 'roleKey',
                align: 'center'
            },
            {
                title: '状态',
                dataIndex: ' status',
                align: 'center',
                render: (_: string | number, row: rowData) => {
                    if (row.status !== 0 && !row.status) return _
                    return <Tag color={row.status === 1 ? 'success' : 'error'}>{row.status === 1 ? '启用' : '禁用'}</Tag>
                }
            },
            {
                title: '创建时间',
                dataIndex: 'createTime',
                align: 'center'
            },
            {
                title: '备注',
                dataIndex: 'remark',
                align: 'center',
                width: 300,
                ellipsis: {showTitle: false},
                render: (text: string | number) => <HoverTooltip title={text}>{text}</HoverTooltip>
            },
            {
                title: '操作',
                key: 'operation',
                align: 'center',
                width: 200,
                fixed: 'right',
                render: (_: string | number, row: rowData) => {
                    return <Space size="large">
                        <Button type="link" size="small"
                                onClick={() => dialogRoleRef.current?.handleOpenDrawer(2, row)}>编辑</Button>
                        <Popconfirm
                            title="温馨提示"
                            description="是否确认删除该角色?"
                            onConfirm={() => handleDelete(row)}
                            okText="确定"
                            cancelText="取消"
                        >
                            <Button type="link" danger size="small">删除</Button>
                        </Popconfirm>
                    </Space>
                }
            },
        ]
        useActivate(() => {
            console.log('TestFunction: didActivate')
        })

        useUnactivate(() => {
            console.log('TestFunction: willUnactivate')
        })
        React.useEffect(() => {
            const initialize = async () => {
                const resp = await Request.get('/roleList', searchForm)
                setDataList(resp.data.list)
                setTotal(resp.data.total)
            }
            initialize()
        }, [searchForm])
        //查询
        const onFinish = (values: Record<string, any>) => {
            setSelectedRowKeys([])
            setSearchForm({...searchForm, ...formatDateParams({params: filterParams(values), labelName: 'createTime'})})
        };
        //重置
        const onReset = () => {
            form.resetFields();
            setSelectedRowKeys([])
            setSearchForm({pageNo: 1, pageSize: 10})
            setTotal(0)
        };
        //分页查询
        const pageOnChange = (page: number, pageSize: number) => {
            setSearchForm(draft => {
                draft.pageNo = page
                draft.pageSize = pageSize
            })
        }
        //行内删除角色
        const handleDelete = async (row: rowData) => {
            const resp = await Request.delete('/deleteRole', {id: row.id}) as any
            if (resp.code === 200) {
                refresh()
                message.success('删除角色成功')
            }
        }
        //勾选角色数据
        const rowSelection = {
            selectedRowKeys,
            onChange: (newSelectedRowKeys: React.Key[], selectedRows: rowData[]) => {
                setSelectedRowKeys(newSelectedRowKeys)
                setSelectedRow(selectedRows)
            }
        };
        //点击批量删除
        const handleDeleteInBulk = () => {
            modal.confirm({
                title: '温馨提示',
                content: `是否确认删除 ${selectedRow.map(v => v.roleName).join(',')} 吗？`,
                centered: true,
                okText: '确定',
                onOk: async () => {
                    const resp = await Request.delete('/deleteRole', {ids: selectedRow.map(v => v.id)}) as any
                    if (resp.code === 200) {
                        refresh()
                        message.success('批量删除成功')
                    }
                }
            })
        }
        //刷新页面
        const refresh = React.useCallback(() => {
            setSelectedRowKeys([])
            setSearchForm({...searchForm})
        }, [])
        return (
            <>
                <Card title="角色管理" bordered={false} style={{width: '100%'}}>
                    <Form
                        form={form}
                        layout="inline"
                        name="roleForm"
                        onFinish={onFinish}
                    >
                        <Space size="large">
                            <Form.Item name="createTime" label="创建时间">
                                <DatePicker.RangePicker style={{width: '280px'}}/>
                            </Form.Item>
                            <Form.Item name="roleName" label="角色名称">
                                <Input placeholder="请输入角色名称" allowClear style={{width: '200px'}}/>
                            </Form.Item>
                            <Form.Item name="status" label="状态">
                                <Select placeholder="请选择状态" allowClear style={{width: '200px'}}>
                                    {statusList.map(v =>
                                        <Select.Option key={v.value} value={v.value}>{v.name}</Select.Option>)}
                                </Select>
                            </Form.Item>
                            <Form.Item>
                                <Space size="large">
                                    <Button type="primary" icon={<SearchOutlined/>} htmlType="submit">查询</Button>
                                    <Button htmlType="button" icon={<SyncOutlined/>} onClick={onReset}>重置</Button>
                                </Space>
                            </Form.Item>
                        </Space>
                    </Form>
                </Card>
                {/*列表部分*/}
                <Card title="列表展示" bordered={false} style={{width: '100%', marginTop: '20px'}}
                      extra={<Space size="large">
                          <Button type="primary" icon={<PlusOutlined/>}
                                  onClick={() => dialogRoleRef.current?.handleOpenDrawer(1)}>新增角色</Button>
                          <Button type="primary" danger icon={<DeleteOutlined/>} disabled={!selectedRowKeys.length}
                                  onClick={handleDeleteInBulk}>批量删除</Button>
                      </Space>}>
                    <Table columns={columns} rowKey="id" bordered rowSelection={{
                        type: "checkbox",
                        ...rowSelection,
                    }}
                           pagination={usePagination(searchForm, total, pageOnChange)}
                           dataSource={dataList}/>
                </Card>
                {/*新增或编辑角色drawer*/}
                <DialogRole ref={dialogRoleRef} refresh={refresh}/>
            </>
        );
    }
;

export default Role;
